package com.ibest.base.controller;

import com.ibest.base.constant.CacheConstant;
import com.ibest.base.entity.TopicEntity;
import org.redisson.api.LocalCachedMapOptions;
import org.redisson.api.RLocalCachedMap;
import org.redisson.api.RedissonClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/topic")
@CrossOrigin(origins = "*")
public class TopicEntityController {
    @Resource
    private RedissonClient redissonClient;


    @PostMapping("/saveOrUpdateTopicEntity")
    public int saveOrUpdate(@RequestBody TopicEntity topicEntity){
        topicEntity.setCreateTime(LocalDateTime.now());
        RLocalCachedMap<String,Object> localCachedMap=redissonClient.getLocalCachedMap(CacheConstant.LOCAL_CACHE_TOPIC_KEY, LocalCachedMapOptions.defaults());
        Object result=localCachedMap.put(topicEntity.getTopicName(),topicEntity);
        return result==null?1:0;
    }
    @GetMapping("/delTopic/{topicName}")
    public int delete(@PathVariable("topicName") String topicName){
        RLocalCachedMap<String,Object> localCachedMap=redissonClient.getLocalCachedMap(CacheConstant.LOCAL_CACHE_TOPIC_KEY, LocalCachedMapOptions.defaults());
        Object result=localCachedMap.remove(topicName);
        return result==null?0:1;
    }

    @GetMapping("/getTopic/{topicName}")
    public TopicEntity getTopic(@PathVariable("topicName") String topicName){
        RLocalCachedMap<String,Object> localCachedMap=redissonClient.getLocalCachedMap(CacheConstant.LOCAL_CACHE_TOPIC_KEY, LocalCachedMapOptions.defaults());
        return (TopicEntity)localCachedMap.get(topicName);
    }

    @GetMapping("/list")
    public List<TopicEntity> list(){
        List<TopicEntity> result=new ArrayList<>();
        RLocalCachedMap<String,Object> localCachedMap=redissonClient.getLocalCachedMap(CacheConstant.LOCAL_CACHE_TOPIC_KEY, LocalCachedMapOptions.defaults());
        for(Map.Entry en: localCachedMap.entrySet()){
            result.add((TopicEntity)en.getValue());
        }
        return result;
    }


}
